package com.pingan.springboot_es_api.utils;

import com.pingan.springboot_es_api.domain.Filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by Kay on 2018/11/6
 */

// 用于传给dsl.xml语句，进行排序
class SortBean{
    private String sort;
    private String order;
    public SortBean(String sort, String order){
        this.sort = sort;
        this.order = order;
    }

    public SortBean() {
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    @Override
    public String toString() {
        return "SortBean{" +
                "sort='" + sort + '\'' +
                ", order='" + order + '\'' +
                '}';
    }
}

/**
 * 格式化传入参数
 */
public class FilterUtil {
    private static Logger logger = LoggerFactory.getLogger(FilterUtil.class);
    // 根据传入的 参数格式化
    public static Map<String,Object> FilterParam(Filters filters)
    {
        Map<String,Object> params = new HashMap<>();
        // 初始化，0 表示该表 match_all查询, 1表示该表有条件查询
        params.put("basic",0);
        params.put("diagnosis",0);
        params.put("medical",0);
        params.put("exam",0);
        params.put("checkup",0);
        params.put("followup",0);

        // 性别处理
        if(filters.getSex()==null || filters.getSex().isEmpty()){
            logger.debug("sex empty");
        }else {
            params.put("sex" , Arrays.asList(filters.getSex().split(",")));
            params.put("basic",1);
        }

        //年龄处理
        // 根据传入的年龄组 算出 多组 的 出生日期范围，目前age不使用，查询排序都用birth_date
        if(filters.getAge()==null || filters.getAge().isEmpty()){
            logger.debug("age empty");
        }else {
            String[] ages = filters.getAge().split(";");   //   多组  范围 ，"age":"20,30;,10;40,;35"
            List<Map<String,String>> ageRangeList = new ArrayList<>();

            for (String age : ages)
            {
                List<String> ageList = Arrays.asList(age.split(",", -1));
                // 等于age 例如  = 35
                if(ageList.size() == 1){
                    Map<String,String> ageGroup = new HashMap<>();
                    ageGroup.put("gt",GetDateFromAgeUtil.GetSmallDate(Integer.parseInt(ageList.get(0))));
                    ageGroup.put("lte",GetDateFromAgeUtil.GetBigDate(Integer.parseInt(ageList.get(0))));
                    ageRangeList.add(ageGroup);
                }else if (ageList.size() == 2)  // 年龄范围查询
                {
                    if (ageList.get(0).isEmpty())  //   <=  小于等于 age， 例如 ,10  等价于 birth_date > (currentdate - age).small
                    {
                        Map<String,String> ageGroup = new HashMap<>();
                        //给dsl 传入 birth_date的gt值
                        ageGroup.put("gt",GetDateFromAgeUtil.GetSmallDate(Integer.parseInt(ageList.get(1))));
                        ageRangeList.add(ageGroup);
                    }else if (ageList.get(1).isEmpty()){   //  >= 大于等于age ，例如 40, 等价于 birth_date <= (currentdate - age).bigdate
                        Map<String,String> ageGroup = new HashMap<>();
                        //给 dsl 传入 birth_date的lte值
                        ageGroup.put("lte",GetDateFromAgeUtil.GetBigDate(Integer.parseInt(ageList.get(0))));
                        ageRangeList.add(ageGroup);
                    }else {
                        //  20,30   区间[age1,age2]   等价于  (currentdate - age1).smalldate < birth_date <= (currentdate - age2).bigdate
                        Map<String,String> ageGroup = new HashMap<>();
                        //给dsl 传入 birth_date的gt值
                        ageGroup.put("gt",GetDateFromAgeUtil.GetSmallDate(Integer.parseInt(ageList.get(1))));
                        //给 dsl 传入 birth_date的lte值
                        ageGroup.put("lte",GetDateFromAgeUtil.GetBigDate(Integer.parseInt(ageList.get(0))));
                        ageRangeList.add(ageGroup);
                    }
                }
            }
            params.put("age" ,ageRangeList);
            params.put("basic",1);
        }

        // 获得 地区
        if(filters.getRegion()==null || filters.getRegion().isEmpty()){
            logger.debug("region empty");
        }else {
            //"region":"北京,山东,广东"
            params.put("region" ,Arrays.asList(filters.getRegion().split(",")));
            logger.debug("region: " + Arrays.asList(filters.getRegion().split(",")));
            params.put("basic",1);
        }

        //疾病 诊断
        if(filters.getDisease()==null || filters.getDisease().isEmpty()){
            logger.debug("disease empty");
        }else {
            try {
                // "disease":"J00,M47.8,J31.0;感冒,颈椎病,鼻炎"
                String[] diseaseGroup = filters.getDisease().split(";", -1);   // 分隔出疾病的 code  和name
                if(diseaseGroup.length == 2) {
                    params.put("disease_code", diseaseGroup[0].split(","));
                    params.put("disease_name", diseaseGroup[1].split(","));
                    params.put("diagnosis",1);
//                    logger.info("diseaseGroup[0] : " + diseaseGroup[0].toString());
//                    logger.info("diseaseGroup[1] : " + diseaseGroup[1].toString());
                }else
                {
                    logger.debug("disease param error!");
                }
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }

        // 诊断时间筛选
        if(filters.getDiagnosisTime()==null || filters.getDiagnosisTime().isEmpty()){
            logger.debug("DiagnosisTime empty");
        }else {
            try {
                // "diagnosisTime":"2011-01-01 00:00:00,2018-12-03 23:12:32"
                String[] diagnosisTime = filters.getDiagnosisTime().split(",",-1);  // 诊断时间 startDiagnosisTime  endDiagnosisTime
                if(diagnosisTime.length == 2){
                    params.put("startDiagnosisTime",diagnosisTime[0]);
                    params.put("endDiagnosisTime",diagnosisTime[1]);
                    params.put("diagnosis",1);
                    logger.info("diagnosisTime 0: " + diagnosisTime[0] + "  1: " + diagnosisTime[1]);
                }else
                {
                    logger.debug("DiagnosisTime param error!");
                }
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }

        //药品 只查询 code  改为模糊查询
        // 添加药品名称
        if(filters.getMedical()==null || filters.getMedical().isEmpty()){
            logger.debug("medical empty");
        }else {
//            params.put("medical_code" ,filters.getMedical().split(","));
//            params.put("medical",1);
            // 添加药品名称
            try {
                // "medical":"A10AB01,A10BA02,A10BB12;name1,name2,name3"
                String[] medicalGroup = filters.getMedical().split(";", -1);   // 分隔出药品的 code  和name
                if(medicalGroup.length == 2) {
                    // 目前只进行药品编码开头的模糊查询，不支持name查询
                    params.put("medical_code", medicalGroup[0].split(","));
                    params.put("medical_name", medicalGroup[1].split(","));
                    params.put("medical",1);
//                    logger.info("diseaseGroup[0] : " + diseaseGroup[0].toString());
//                    logger.info("diseaseGroup[1] : " + diseaseGroup[1].toString());
                }else
                {
                    logger.debug("medical param error!");
                }
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }

        // sortColumn  组合 sortColumn和sortOrder为  SortBean
        if(filters.getSortColumn()==null || filters.getSortColumn().isEmpty()){
            logger.debug("sortColumn empty");
        }else {
            // "sortColumn":"party_id|age"
            // "sortOrder":"asc|desc"
            String[] sortColumns = filters.getSortColumn().split("\\|");
            String[] orders = filters.getSortOrder().split("\\|");
            int sortLength = sortColumns.length;
//            int orderLength = orders.length;
            List<SortBean> sortList = new ArrayList<>();
            // 默认sortLength  == orderLength
            for (int i =0 ; i< sortLength ; i++){
//                    sortMap.put(sortColumns[i],orders[i]);
//                Map<String,String> sortMap = new HashMap<>();
                SortBean sortBean = new SortBean();
                // 如果是 birth_date 排序，传递的排序方式是年龄的排序方式，所以修改排序方式 变为 相反的，
                if (sortColumns[i].equals("birth_date")){
                    sortBean.setSort("birth_date");
                    sortBean.setOrder(orders[i].equals("asc")?"desc":"asc");
                }else {
                    sortBean.setSort(sortColumns[i]);
                    sortBean.setOrder(orders[i]);
                }
                sortList.add(sortBean);
            }
//            logger.info("sortList : " + sortList.toString());
            params.put("sortColumn" ,sortList);
        }

        //默 认  from  = 0  size = 20
        Long size = 20l;
        Long from = 0l;
        //pageSize  // 每页大小
        if(filters.getPageSize()==null ){
            logger.debug("pageSize empty");
        }else {
            size = filters.getPageSize();
            //currentPage   第几页 0 为第一页
            if(filters.getCurrentPage()==null ){
                logger.debug("currentPage empty");
            }else {
                from = (filters.getCurrentPage() - 1) * size ;
                params.put("from" ,from);
                params.put("size" ,size);
            }
        }
        params.put("from" ,from);
        params.put("size" ,size);

        logger.debug("params : " + params.toString());
//        logger.info("filters string : " + filters.toString());
//        logger.info("params :" + params.toString());
        return params;
    }
}
